package com.augurit.smartform.display;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.smartform.constant.FreeMarkerConstant;
import com.augurit.smartform.constant.PageConstant;
import com.augurit.smartform.constant.TypeConstant;
import com.augurit.smartform.service.ISmartFormService;

@Component
public class PageResolve {
	@Autowired
	private ISmartFormService smartFormService;
	@Autowired
	private ISysCodeService sysCodeService;
	
	public PageElement paser(String sourceXmlStr){
		PageElement page=new PageElement();
		Document document=this.getDocument(sourceXmlStr);
//		List<Element> objects=(List<Element>)document.selectNodes("//objects/object");
//		Element element=(Element)objects.get(0);
		Element element=document.getRootElement();
		this.parseElementToPage(element, page);
		this.adjustPageAttribute(page);
		List<Element> fields=(List<Element>)document.selectNodes("//field");
		this.parseFieldsToPage(page, fields);
		this.sortElement(page);
		
		return page;
	}
	
	/**
	 * 初始化DOM4J的DOCUMENT对象
	 * @param xmlStr
	 * cuigeqiang
	 */
	private Document getDocument(String xmlStr){
		Document document=null;
		try {
			document=DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document;
	}
	
	/**
	 * 将ELEMENT元素转换为PAGE对象
	 * @param element
	 * @param page
	 * cuigeqiang
	 */
	private void parseElementToPage(Element element,PageElement page){
		Iterator attrs=element.attributeIterator();
		this.parseAttrIteratorToPageAttr(page, attrs);
	}
	
	/**
	 * 将DOM4J属性转换为PAGE属性
	 * @param page
	 * @param attrs
	 * cuigeqiang
	 */
	private void parseAttrIteratorToPageAttr(PageElement page,Iterator attrs){
		while(attrs.hasNext()){
			Attribute attr=(Attribute)attrs.next();
			if("name".equals(attr.getName())){
				page.setName(attr.getValue().toLowerCase());
			}else if("cnName".equals(attr.getName())){
				page.setCnName(attr.getValue());
			}else if("pageCode".equals(attr.getName())){
				page.setPageCode(attr.getValue());
			}else if("id".equals(attr.getName())){
				page.setPageId(attr.getValue());
			}else if("formType".equals(attr.getName())){
				page.setFormType(attr.getValue());
			}
		}
	}
	
	/**
	 * 调整页面的属性
	 * @param page
	 * cuigeqiang
	 */
	private void adjustPageAttribute(PageElement page){
		String sourceName=page.getPageCode()+FreeMarkerConstant.FTL_SUFFIX;
		page.setSourceName(sourceName);
		String sourcePath=FreeMarkerConstant.SOURCE+FreeMarkerConstant.FILE_COMMON_SLASH+sourceName;
		page.setSourcePath(sourcePath);
		String jspName=page.getPageCode()+FreeMarkerConstant.JSP_SUFFIX;
		page.setJspName(jspName);
		String jspPath=FreeMarkerConstant.OUTPUT+FreeMarkerConstant.FILE_COMMON_SLASH+jspName;
		page.setJspPath(jspPath);
	}
	
	/**
	 * 将字段注入到PAGE属性中
	 * @param page
	 * @param fields
	 * cuigeqiang
	 */
	private void parseFieldsToPage(PageElement page,List<Element> fields){
		for(int i=0;i<fields.size();i++){
			Element field=fields.get(i);
			Iterator attrs=field.attributeIterator();
			TagElement tag=new TagElement();
			tag.setXmlStr(field.asXML());
			Element parentField=field.getParent();
			if(parentField!=null){													//设置PAGENAME属性为OBJECT标签的NAME属性
				String objectName=parentField.attributeValue("name");
				if(StringUtils.isNotBlank(objectName)){
					tag.setPageName(objectName);
				}
			}
			if(StringUtils.isBlank(tag.getPageName())){
				tag.setPageName(page.getName());
			}
			this.parseAttrIteratorToTagAttr(tag, attrs);
			this.injectOptions(tag);												//给SELECT标签注入OPTIONS选项
			this.injectDefaultSort(tag);											//给标签加入默认的排序顺序
			page.setElements(tag.getId(), tag);
		}
	}
	
	/**
	 * 将FIELD属性注入到TAG对象中
	 * @param tag
	 * @param attrs
	 * cuigeqiang
	 */
	private void parseAttrIteratorToTagAttr(TagElement tag,Iterator attrs){
		while(attrs.hasNext()){
			Attribute attr=(Attribute)attrs.next();
			if("id".equals(attr.getName())){
				tag.setId(attr.getValue());
			}else if("name".equals(attr.getName())){
				tag.setName(attr.getValue());
			}else if("cnName".equals(attr.getName())){
				tag.setTitle(attr.getValue());
			}else if("isUnique".equals(attr.getName())){
				if("true".equalsIgnoreCase(attr.getValue())){
					tag.setUnique(true);
				}
			}else if("isNotNull".equals(attr.getName())){
				if("true".equalsIgnoreCase(attr.getValue())){
					tag.setNotNull(true);
				}
			}else if("defaultValue".equals(attr.getName())){
				tag.setDefaultValue(attr.getValue());
			}else if("value".equals(attr.getName())){
				tag.setValue(attr.getValue());
			}else if("dictionary".equals(attr.getName())){
				tag.setDictionary(attr.getValue());
			}else if("style".equals(attr.getName())){
				tag.setStyle(attr.getValue());
			}else if("cssClass".equals(attr.getName())){
				tag.setCssClass(attr.getValue());
			}else if("checked".equals(attr.getName())){
				if("true".equalsIgnoreCase(attr.getValue())){
					tag.setChecked(true);
				}
			}else if("tag".equals(attr.getName())){
				tag.setType(attr.getValue());
			}else if("sort".equals(attr.getName())){
				if(StringUtils.isNotBlank(attr.getValue())){
					tag.setSort(Integer.valueOf(attr.getValue()));
				}
			}else if("maxlength".equals(attr.getName())){
				tag.setMaxlength(attr.getValue());
			}else if("size".equals(attr.getName())){
				tag.setSize(attr.getValue());
			}else if("rows".equals(attr.getName())){
				tag.setRows(attr.getValue());
			}else if("cols".equals(attr.getName())){
				tag.setCols(attr.getValue());
			}else if("align".equals(attr.getName())){
				tag.setAlign(attr.getValue());
			}else if("list".equals(attr.getName())){
				tag.setList(attr.getValue());
			}else if("listKey".equals(attr.getName())){
				tag.setListKey(attr.getValue());
			}else if("listValue".equals(attr.getName())){
				tag.setListValue(attr.getValue());
			}else if("activities".equals(attr.getName())){
				tag.setActivities(attr.getValue());
			}else if("format".equals(attr.getName())){
				tag.setFormat(attr.getValue());
			}else if("debug".equals(attr.getName())){
				tag.setDebug(attr.getValue());
			}else if("sendFieldId".equals(attr.getName())){
				tag.setSendFieldId(attr.getValue());
			}else if("judgmentDivId".equals(attr.getName())){
				tag.setJudgmentDivId(attr.getValue());
			}else if("template".equals(attr.getName())){
				tag.setTemplate(attr.getValue());
			}else if("onclick".equals(attr.getName())){
				tag.setOnclick(attr.getValue());
			}else if("ondblclick".equals(attr.getName())){
				tag.setOndblclick(attr.getValue());
			}else if("onmousedown".equals(attr.getName())){
				tag.setOnmousedown(attr.getValue());
			}else if("onmouseup".equals(attr.getName())){
				tag.setOnmouseup(attr.getValue());
			}else if("onmouseover".equals(attr.getName())){
				tag.setOnmouseover(attr.getValue());
			}else if("onmousemove".equals(attr.getName())){
				tag.setOnmouseover(attr.getValue());
			}else if("onmouseout".equals(attr.getName())){
				tag.setOnmouseout(attr.getValue());
			}else if("onfocus".equals(attr.getName())){
				tag.setOnfocus(attr.getValue());
			}else if("onblur".equals(attr.getName())){
				tag.setOnblur(attr.getValue());
			}else if("onkeypress".equals(attr.getName())){
				tag.setOnkeypress(attr.getValue());
			}else if("onkeydown".equals(attr.getName())){
				tag.setOnkeydown(attr.getValue());
			}else if("onkeyup".equals(attr.getName())){
				tag.setOnkeyup(attr.getValue());
			}else if("onselect".equals(attr.getName())){
				tag.setOnselect(attr.getValue());
			}else if("onchange".equals(attr.getName())){
				tag.setOnchange(attr.getValue());
			}else if("name1".equals(attr.getName())){
				tag.setName1(attr.getValue());
			}else if("name2".equals(attr.getName())){
				tag.setName2(attr.getValue());
			}
		}	
	}
	
	/**
	 * 向SELECT注入OPTIONS选项
	 * @param tag
	 * cuigeqiang
	 */
	private void injectOptions(TagElement tag){
		if((TypeConstant.LIST.equalsIgnoreCase(tag.getType())||TypeConstant.SELECT.equalsIgnoreCase(tag.getType()))&&StringUtils.isNotBlank(tag.getDictionary())){
			List<SysCodeForm> sysCodes=sysCodeService.getItems(tag.getDictionary());
			tag.getOptions().addAll(sysCodes);
		}
	}
	
	/**
	 * 向SELECT注入OPTIONS选项
	 * @param tag
	 * cuigeqiang
	 */
	private void injectDefaultSort(TagElement tag){
		if(tag.getSort()==null){
			tag.setSort(100);
		}
	}
	
	/**
	 * 对字段进行排序
	 * @param page
	 * cuigeqiang
	 */
	private void sortElement(PageElement page){
		Map<String,TagElement> elements=page.getElements();
		List<TagElement> list=new ArrayList<TagElement>();
		Iterator<TagElement> it=elements.values().iterator();
		while(it.hasNext()){
			list.add(it.next());
		}
		Collections.sort(list, new Comparator(){
			public int compare(Object o1, Object o2) {
				TagElement tag1=(TagElement)o1;
				TagElement tag2=(TagElement)o2;
				return tag1.getSort().compareTo(tag2.getSort());
			}
		});
		elements.clear();
		for(TagElement tag : list){
			elements.put(tag.getId(), tag);
		}
	}
}
